'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { pk_id, user_id, accept } = event;
  try {
    if (!pk_id || !user_id) {
      return { code: -1, msg: 'PK ID 或用户ID不能为空' };
    }

    const pkCollection = db.collection('pk_records');
    const pkRes = await pkCollection.doc(pk_id).get();
    if (!pkRes.data) {
      return { code: -1, msg: 'PK记录不存在' };
    }
    const pk = pkRes.data;

    console.log('PK记录:', pk, '操作用户:', user_id);

    if (pk.opponent_id !== user_id) {
      return { code: -1, msg: '无权操作此PK' };
    }

    if (pk.status !== 'pending') {
      return { code: -1, msg: '挑战状态无效，仅可操作待处理挑战' };
    }

    if (accept) {
      const questionRes = await db.collection('questions').aggregate().sample({ size: 10 }).end();
      const questions = questionRes.data;
      if (!questions.length) {
        return { code: -1, msg: '题目不足，无法开始挑战' };
      }

      await pkCollection.doc(pk_id).update({
        status: 'accepted',
        questions: questions.map(q => ({
          _id: q._id,
          content: q.content,
          options: q.options,
          answer: q.answer
        })),
        updated_at: new Date()
      });

      console.log('接受挑战成功:', { pk_id, user_id });
      return {
        code: 0,
        data: { questions },
        msg: '已接受挑战'
      };
    } else {
      await pkCollection.doc(pk_id).update({
        status: 'rejected',
        updated_at: new Date()
      });
      console.log('拒绝挑战成功:', { pk_id, user_id });
      return { code: 0, msg: '已拒绝挑战' };
    }
  } catch (e) {
    console.error('处理PK失败:', e);
    return { code: -1, msg: `处理PK失败: ${e.message || '未知错误'}` };
  }
};